package com.sgb.kjwl.view.ui.activity.self.publish;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.swgk.core.event.MessageEvent;
import com.sgb.kjwl.databinding.ActivityGoodsDetailBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.Bean;
import com.sgb.kjwl.model.entity.CompanyDetailsEntity;
import com.sgb.kjwl.model.entity.NewGoodsDetailEntity.SelectArr.SkuCombinationEntity.CombinationList;
import com.sgb.kjwl.model.entity.NewGoodsDetailEntity;
import com.sgb.kjwl.model.entity.ParamsEntity;
import com.sgb.kjwl.model.entity.SkuCheckEntity;
import com.sgb.kjwl.model.entity.SkuCombinationEntity;
import com.sgb.kjwl.model.entity.VideoEntity;
import com.sgb.kjwl.model.entity.user.ServerAttrValue;
import com.sgb.kjwl.model.entity.user.SkuItemAttrEntity;
import com.sgb.kjwl.utils.PointUtils;
import com.swgk.core.util.UiUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.GoodsEvent;
import com.sgb.kjwl.view.ui.adapter.material.GoodsSkuAdapter;
import com.sgb.kjwl.view.ui.adapter.shopping.AttrAdapter;
import com.sgb.kjwl.view.ui.adapter.shopping.IndicatorAdapter;
import com.sgb.kjwl.view.widget.GoodsDetailPriceDialog3;
import com.sgb.kjwl.view.widget.SelfGoodAttrWindow;
import com.sgb.kjwl.view.widget.SelfShoppingDetailAttrWindow;
import com.sgb.kjwl.viewmodel.self.publish.GoodsDetailModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.CommonDialog;
import com.zhy.view.flowlayout.TagAdapter;

import org.apache.commons.lang3.StringEscapeUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.nodes.Document;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import cn.jzvd.Jzvd;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

import static com.swgk.core.event.EventConstant.EVENT_GOODS_PUBLISH;

/**
 * 商品详情（我的-商品报价-商品列表）
 *
 * @author 陈方凯
 */
public class GoodsDetailActivity extends AppActivity {
    private ActivityGoodsDetailBinding binding;
    private String id;
    private String arr = "";
    //视频
    private SensorManager sensorManager;
    private SensorEventListener sensorEventListener;
    private List<ParamsEntity> list = new ArrayList<>();
    List<String> videos = new ArrayList<>();
    private List<String> mSelect = new ArrayList<>();
    private AttrAdapter mAttrAdapter;
    private GoodsSkuAdapter goodsSkuAdapter;
    private int mLastIndex;
    private SelfShoppingDetailAttrWindow goodSAttributeWindow;
    private SelfGoodAttrWindow goodSSkuWindow;
    private double itemNum = 1;
    private boolean isFirst = false;
    private boolean isShowFirst = false;
    List<SkuCheckEntity> check = new ArrayList<>();
    /***
     * 供应商详情
     */
    private CompanyDetailsEntity companyDetailsEntity;
    Document htmlResult;
    @Inject
    GoodsDetailModel viewModel;
    public static final String OPT_UP = "1";
    public static final String OPT_DOWN = "2";
    public static final String OPT_DEL = "3";
    private List<SkuItemAttrEntity> itemAttrEntityList = new ArrayList<>();
    private List<String> keyList = new ArrayList<>();
    private List<SkuItemAttrEntity.Child> childList = new ArrayList<>();
    private Map<String, SkuItemAttrEntity.Child> itemMap = new HashMap<>();
    List<SkuCombinationEntity> skuCombinationEntities = new ArrayList<>();
    List<ParamsEntity> paramsEntities;
    private String[] titls = new String[]{"商品详情", "其他信息"};

    public static void start(Context context, String id) {
        Intent intent = new Intent(context, GoodsDetailActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(GoodsDetailActivity.this, R.layout.activity_goods_detail);
        binding.setViewModel(viewModel);
        binding.modifyLayout.setOnClickListener(this);
        binding.upLayout.setOnClickListener(this);
        binding.delLayout.setOnClickListener(this);
        binding.downLayout.setOnClickListener(this);
        binding.llShopInfo.setOnClickListener(this);
        binding.rlGg.setOnClickListener(this);
        binding.tvEdit.setOnClickListener(this);
        binding.backView.setOnClickListener(this);
        binding.backViewToolBar.setOnClickListener(this);
        binding.companyInfoLayout.setOnClickListener(this);
        setToolBar();
        goodSAttributeWindow = new SelfShoppingDetailAttrWindow(GoodsDetailActivity.this);
        goodSAttributeWindow.setBgView(binding.grayLayout);
        goodSAttributeWindow.setOnResultClick((key1, key2, key3) -> {
        });

        binding.rvSelect.setLayoutManager(new LinearLayoutManager(UiUtil.getContext(), RecyclerView.HORIZONTAL, false));
        mAttrAdapter = new AttrAdapter(mSelect);
        binding.rvSelect.setAdapter(mAttrAdapter);

        goodSSkuWindow = new SelfGoodAttrWindow(GoodsDetailActivity.this);
        goodSSkuWindow.setBgView(binding.grayLayout);
        goodSSkuWindow.setOnResultClick((key1, key2, key3) -> {
//            if (!"0.00".equals((String) key1))
            if(key1!=null&&!TextUtils.isEmpty((String)key1)) {
                binding.priceTv.setText("¥" + (String) key1 + "/" + viewModel.newGoodsDetailEntity.get().getUnit());
            }else{
                binding.priceTv.setText("无货");
            }
            if(!TextUtils.isEmpty(key3.toString())){
                binding.tvMoney.setText("¥" + PointUtils.price(Double.parseDouble((String)key3)) + "/" + viewModel.newGoodsDetailEntity.get().getUnit());
                binding.tvMoney.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                binding.tvMoney.setVisibility(View.VISIBLE);
            }else{
                binding.tvMoney.setVisibility(View.GONE);
            }
            setDate((String) key2);
        });
        goodsSkuAdapter = new GoodsSkuAdapter(this, null);
        binding.tablayout2.addTab(binding.tablayout2.newTab().setText(titls[0]));
        binding.tablayout2.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (binding.llWv.getChildCount() > 0) {
                    binding.llWv.removeAllViews();
                }
                if (tab.getPosition() == 0) {
                    // TODO: 2020/12/15 0015
                    binding.clCompany.setVisibility(View.GONE);
                    if (viewModel.newGoodsDetailEntity.get() != null && !TextUtils.isEmpty(viewModel.newGoodsDetailEntity.get().getItemDetail())) {
                        setHtml(viewModel.newGoodsDetailEntity.get().getItemDetail());
                    } else {
                        binding.empty.setVisibility(View.VISIBLE);
                    }
                    if (viewModel.newGoodsDetailEntity.get().getVideoList() != null && videos.size() > 0) {
                        binding.flVideo.setVisibility(View.VISIBLE);
                        binding.empty.setVisibility(View.GONE);
                    }
                } else {
                    binding.flVideo.setVisibility(View.GONE);
                    binding.empty.setVisibility(View.GONE);
                    showWebView(StringEscapeUtils.unescapeJava(viewModel.newGoodsDetailEntity.get().getItemTitleUrl()));
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    private void setDate(String date) {
        mSelect.clear();
        String datas = date;
        String[] s = datas.split("、");
        for (String str : s) {
            mSelect.add(str);
        }
        mAttrAdapter.setNewData(mSelect);
        binding.llSelect.setVisibility(View.VISIBLE);
    }

    private void showAttrPop() {
        if (!isShowFirst) {
            isShowFirst = true;
            NewGoodsDetailEntity.SelectArr.SkuCombinationEntity skuCombinationEntity = new NewGoodsDetailEntity.SelectArr.SkuCombinationEntity();
            List<CombinationList> combinationLists = new ArrayList<>();
            if (itemAttrEntityList.size() > 0) {
                for (int i = 0; i < itemAttrEntityList.size(); i++) {
                    SkuItemAttrEntity skuItemAttrEntity = itemAttrEntityList.get(i);
                    CombinationList combinationList = new CombinationList();
                    combinationList.setName(skuItemAttrEntity.getParamData());
                    String str = "";
                    if (skuItemAttrEntity.getList() != null) {
                        for (int j = 0; j < skuItemAttrEntity.getList().size(); j++) {
                            if (j == skuItemAttrEntity.getList().size() - 1) {
                                str += skuItemAttrEntity.getList().get(j).getValData();
                            } else {
                                str += skuItemAttrEntity.getList().get(j).getValData() + "、";
                            }
                        }
                    }
                    combinationList.setVal(str);
                    combinationLists.add(combinationList);
                }
            }
            if (paramsEntities != null && paramsEntities.size() > 0) {
                for (int i = 0; i < paramsEntities.size(); i++) {
                    CombinationList combinationList = new CombinationList();
                    combinationList.setName(paramsEntities.get(i).getKey());
                    combinationList.setVal(paramsEntities.get(i).getValue());
                    combinationLists.add(combinationList);
                }
            }
            if (combinationLists.size() > 0) {
                skuCombinationEntity.setList(combinationLists);
                goodSAttributeWindow.setData(skuCombinationEntity);
            }
        }
        goodSAttributeWindow.showDownPopwindow(binding.grayLayout, true);
    }

    private void showSkuPop() {
        if (!isFirst) {
            if (viewModel.newGoodsDetailEntity.get().getCommoditySku() != null && viewModel.newGoodsDetailEntity.get().getCommoditySku().getList().size() > 0) {
                String data = "";
                for (NewGoodsDetailEntity.commoditySkuListItem commoditySkuListItem : viewModel.newGoodsDetailEntity.get().getCommoditySku().getList()) {
                    data = data + commoditySkuListItem.getVal() + "、";
                }
                data = data.substring(0, data.length() - 1);//去除末尾的、
                setDate(data);
                goodSSkuWindow.setData(viewModel.newGoodsDetailEntity.get(), itemAttrEntityList, skuCombinationEntities, viewModel.newGoodsDetailEntity.get().getCommoditySku().getList(),viewModel.newGoodsDetailEntity.get().getMinPrice() + "/" + viewModel.newGoodsDetailEntity.get().getUnit(),data);
            } else {
                goodSSkuWindow.setData(viewModel.newGoodsDetailEntity.get(), itemAttrEntityList, skuCombinationEntities);
            }
            isFirst = true;
        }
        goodSSkuWindow.showDownPopwindow(binding.grayLayout, true);
    }

    //banner
    private void initBanner(NewGoodsDetailEntity data) {
        // 轮播图
        List<String> urls = new ArrayList<>();
        List<Bean> indicator = new ArrayList<>();
        boolean isHasVideo = false;
        if (data.getVideoList() != null && data.getVideoList().size() > 0) {
            for (int i = 0; i < data.getVideoList().size(); i++) {
                String key = "视频";
                if (data.getVideoList().get(i).type == 1) {
                    String video = data.getVideoList().get(i).playUrl + key +
                            data.getVideoList().get(i).playUrlImg + key +
                            data.getVideoList().get(i).time + key
                            + data.getVideoList().get(i).videoName;
                    urls.add(video);
                    if (TextUtils.isEmpty(data.getVideoList().get(i).playUrlImg)) {
                        isHasVideo = true;
                        indicator.add(new Bean(data.getVideoList().get(i).playUrl, 1));
                    } else {
                        indicator.add(new Bean(data.getVideoList().get(i).playUrlImg, 1));
                    }
                }
            }
        }
        binding.rv.setLayoutManager(new LinearLayoutManager(UiUtil.getContext(), RecyclerView.HORIZONTAL, false));
        for (String img : data.getImages()) {
            indicator.add(new Bean(img, 0));
            urls.add(img);
        }
        indicator.get(0).select = true;
        IndicatorAdapter adapter = new IndicatorAdapter(indicator);
        adapter.setIsHasVideo(isHasVideo);
        binding.rv.setAdapter(adapter);
        binding.tvPosition.setText(1 + "");
        binding.tvCount.setText(indicator.size() + "");
        binding.banner.initBannerImageView(urls, false, false, 0);
        binding.banner.onSel(index -> {
            if (mLastIndex == index) {
                return;
            }
            if (index != 0) {
                Jzvd.releaseAllVideos();
            }
            binding.tvPosition.setText(index + 1 + "");
            adapter.getData().get(index).select = true;
            adapter.getData().get(mLastIndex).select = false;
            mLastIndex = index;
            adapter.notifyDataSetChanged();
        });
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            if (mLastIndex == position) {
                return;
            }
            if (position != 0) {
                Jzvd.releaseAllVideos();
            }
            binding.tvPosition.setText(position + 1 + "");
            binding.tvCount.setText(indicator.size() + "");
            binding.banner.mRecyclerView.scrollToPosition(position);
            adapter.getData().get(position).select = true;
            adapter.getData().get(mLastIndex).select = false;
            mLastIndex = position;
            adapter.notifyDataSetChanged();
        });

    }

    private void videos(NewGoodsDetailEntity data) {
        videos.clear();
        // NormalRecyclerAdapter 视频和图片处理
        if (data.getVideoList() != null && data.getVideoList().size() != 0) {
            for (VideoEntity videoBean : data.getVideoList()) {
                if (videoBean.type != 1) {
                    videos.add(videoBean.playUrl + "视频" + videoBean.playUrlImg);
                }
            }
        }
        binding.tvPos.setText(1 + "");
        binding.tvSum.setText(videos.size() + "");
        binding.flVideo.setVisibility(videos.size() == 0 ? View.GONE : View.VISIBLE);
        binding.empty.setVisibility(videos.size() == 0 ? View.VISIBLE : View.GONE);
        binding.bannerVideo.initBannerImageView(videos, true, false, 1);
        binding.bannerVideo.onSel(index -> binding.tvPos.setText(index + 1 + ""));
    }

    @Override
    protected void init() {
        id = getIntent().getStringExtra("id");
        viewModel.getGoodsDetail(id);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new JCVideoPlayer.JCAutoFullscreenListener();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void initData() {
        if (viewModel.newGoodsDetailEntity.get() != null && !TextUtils.isEmpty(viewModel.newGoodsDetailEntity.get().getItemTitleUrl())) {
            if (binding.tablayout2.getTabCount() == 1) {
                binding.tablayout2.addTab(binding.tablayout2.newTab().setText(titls[1]));
            }
        } else {
            binding.tablayout2.setVisibility(View.GONE);
            binding.tvDetail.setVisibility(View.VISIBLE);
        }
        list.clear();
        arr = "";
        setItemAttrEntityList();
        paramsEntities = viewModel.newGoodsDetailEntity.get().getOriginItemAttr();
        if (itemAttrEntityList.size() > 0) {
            for (int i = 0; i < itemAttrEntityList.size(); i++) {
                arr += itemAttrEntityList.get(i).getParamData() + "、";
            }
        }
        if (paramsEntities != null && paramsEntities.size() > 0) {
            for (int i = 0; i < paramsEntities.size(); i++) {
                arr += paramsEntities.get(i).getKey() + "、";
            }
        }

        binding.tvStatus.setText(viewModel.newGoodsDetailEntity.get().getStatus());
        if (viewModel.newGoodsDetailEntity.get().getStatus().equals("已上架")) {
            binding.tvStatus.setBackground(getResources().getDrawable(R.drawable.corner_blue_shape));
            binding.upLayout.setVisibility(View.GONE);
            binding.downLayout.setVisibility(View.VISIBLE);
            binding.tvEdit.setTextColor(getResources().getColor(R.color.new_blue_50));
        } else if (viewModel.newGoodsDetailEntity.get().getStatus().equals("已下架")) {
            binding.tvStatus.setBackground(getResources().getDrawable(R.drawable.corner_gray_shape));
            binding.upLayout.setVisibility(View.VISIBLE);
            binding.downLayout.setVisibility(View.GONE);
            binding.tvEdit.setTextColor(getResources().getColor(R.color.new_blue));
        } else {
            binding.tvStatus.setBackground(getResources().getDrawable(R.drawable.corner2_c0c4cc_full_bg));
            binding.upLayout.setVisibility(View.GONE);
            binding.downLayout.setVisibility(View.GONE);
        }
        binding.tvCount.setText(viewModel.newGoodsDetailEntity.get().getImages().size() + "");
        binding.priceTv.setText("¥" + viewModel.newGoodsDetailEntity.get().getMinPrice() + "/" + viewModel.newGoodsDetailEntity.get().getUnit());
        if (1==viewModel.newGoodsDetailEntity.get().getPromoteStatus()) {
            binding.tvMoney.setText("¥" + PointUtils.price(viewModel.newGoodsDetailEntity.get().getCommoditySku().getMoney()) + "/" + viewModel.newGoodsDetailEntity.get().getUnit());
            binding.tvMoney.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
            binding.tvMoney.setVisibility(View.VISIBLE);
        }else{
            binding.tvMoney.setVisibility(View.GONE);
        }

        binding.minBuyQuantity.setText(viewModel.newGoodsDetailEntity.get().getLowestbuy());
        if (TextUtils.isEmpty(arr)) {
            binding.llShopInfo.setVisibility(View.GONE);
            binding.rlGg.setVisibility(View.GONE);
            binding.llSelect.setVisibility(View.GONE);
        } else {
            binding.tvShopInfo.setText(arr.substring(0, arr.length() - 1));
        }
        if ("1".equals(viewModel.newGoodsDetailEntity.get().getCommodityType())) {
            binding.itemTvFutures.setText("现货");
        } else if ("2".equals(viewModel.newGoodsDetailEntity.get().getCommodityType())) {
            if ("1".equals(viewModel.newGoodsDetailEntity.get().getDeliveryTimeUnit())) {
                binding.itemTvFutures.setText(viewModel.newGoodsDetailEntity.get().getDeliveryTime() + "日");
            } else {
                binding.itemTvFutures.setText(viewModel.newGoodsDetailEntity.get().getDeliveryTime() + "个月");
            }
        } else {
            binding.dataView.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(viewModel.newGoodsDetailEntity.get().getBrandName())) {
            binding.brandLayout.setVisibility(View.GONE);
        } else {
            binding.brandLayout.setVisibility(View.VISIBLE);
        }

        if (viewModel.newGoodsDetailEntity.get().getCommoditySku() != null && viewModel.newGoodsDetailEntity.get().getCommoditySku().getList().size() > 0) {
            String data = "";
            for (NewGoodsDetailEntity.commoditySkuListItem commoditySkuListItem : viewModel.newGoodsDetailEntity.get().getCommoditySku().getList()) {
                data = data + commoditySkuListItem.getVal() + "、";
            }
            data = data.substring(0, data.length() - 1);//去除末尾的、
            setDate(data);
        }

        initBanner(viewModel.newGoodsDetailEntity.get());
        videos(viewModel.newGoodsDetailEntity.get());
        setGoodsOtherService(viewModel.newGoodsDetailEntity.get());
        setHtml(viewModel.newGoodsDetailEntity.get().getItemDetail());
    }

    /**
     * 商品其他服务
     *
     * @param newGoodsDetailEntity
     */
    private void setGoodsOtherService(NewGoodsDetailEntity newGoodsDetailEntity) {
        List<ServerAttrValue> itemServerAttrVals = newGoodsDetailEntity.getItemServerAttrVals();
        if (itemServerAttrVals == null || itemServerAttrVals.size() == 0) {
            return;
        }
        for (ServerAttrValue attrValue : itemServerAttrVals) {
            if (attrValue.getServiceType() == 1) {
                List<ServerAttrValue.GoodsServiceOtherAttr> attrValueValue = attrValue.getValue();
                if (attrValueValue != null && attrValueValue.size() != 0) {
                    setGoodsOtherService(attrValueValue);
                }
                break;
            }
        }
    }

    private void setGoodsOtherService(List<ServerAttrValue.GoodsServiceOtherAttr> attrList) {
        List<ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue> attrValueArrayList = new ArrayList<>();
        for (ServerAttrValue.GoodsServiceOtherAttr otherAttrValue : attrList) {
            List<ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue> otherAttrValueValue = otherAttrValue.getValue();
            if (otherAttrValueValue != null && otherAttrValueValue.size() != 0) {
                for (ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue oav : otherAttrValueValue) {
                    if (oav.getChecked() == 1) {
                        attrValueArrayList.add(oav);
                    }
                }
            }
        }
        if (attrValueArrayList.size() > 0) {
            binding.tagContainer.setVisibility(View.VISIBLE);
            showGoodsOtherService(attrValueArrayList);
        }
    }

    private void showGoodsOtherService(List<ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue> attrValueArrayList) {
        TagAdapter<ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue> attrAdapter = new TagAdapter<ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue>(attrValueArrayList) {
            @Override
            public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, ServerAttrValue.GoodsServiceOtherAttr.OtherAttrValue otherAttrValue) {
                final LayoutInflater mInflater = LayoutInflater.from(GoodsDetailActivity.this);
                LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_goods_service_other, binding.tagContainer, false);
                TextView tv = layout.findViewById(R.id.item_attr);
                tv.setText(otherAttrValue.getAttributeName());
                return layout;
            }
        };
        binding.tagContainer.setAdapter(attrAdapter);
    }

    public void setHtml(String htmls) {
        if (!TextUtils.isEmpty(htmls)) {
            binding.empty.setVisibility(View.GONE);
            WebView webView1 = new WebView(GoodsDetailActivity.this);
            WebSettings webSettings = webView1.getSettings();
            webSettings.setUseWideViewPort(true);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            binding.llWv.setVisibility(View.VISIBLE);
            webView1.setHorizontalScrollBarEnabled(false);
            webView1.setVerticalScrollBarEnabled(false);
            webView1.loadDataWithBaseURL(null, setWebViewContent(viewModel.newGoodsDetailEntity.get().getItemDetail()), "text/html", "UTF-8", null);
            webView1.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            webView1.measure(0, 0);
                            int measuredHeight = webView1.getMeasuredHeight();
                            ViewGroup.LayoutParams layoutParams = webView1.getLayoutParams();
                            layoutParams.height = measuredHeight;
                            webView1.setLayoutParams(layoutParams);
                        }
                    }, 1000);
                }
            });
            webView1.requestLayout();
            binding.llWv.addView(webView1);
            webView1.requestLayout();
        } else {
            binding.llWv.setVisibility(View.GONE);
        }
    }

    private String setWebViewContent(String content) {
        String head = "<style type=\"text/css\"> img {" +
                "width:100%;" +//限定图片宽度填充屏幕
                "height:auto;" +//限定图片高度自动
                "}" +
                "body {" +
                "margin-right:15px;" +//限定网页中的文字右边距为15px(可根据实际需要进行行管屏幕适配操作)
                "margin-left:15px;" +//限定网页中的文字左边距为15px(可根据实际需要进行行管屏幕适配操作)
                "margin-top:15px;" +//限定网页中的文字上边距为15px(可根据实际需要进行行管屏幕适配操作)
                "font-size:38px;" +//限定网页中文字的大小为40px,请务必根据各种屏幕分辨率进行适配更改
                "word-wrap:break-word;" +//允许自动换行(汉字网页应该不需要这一属性,这个用来强制英文单词换行,类似于word/wps中的西文换行)
                "}" +
                "</style>";
        return "<html><header>" + head + "</header>" + content + "</html>";
    }

    private void setItemAttrEntityList() {
        keyList.clear();
        itemAttrEntityList.clear();
        if (viewModel.newGoodsDetailEntity.get().getCheckedItemAttr() != null && viewModel.newGoodsDetailEntity.get().getCheckedItemAttr().getList() != null) {
            for (int i = 0; i < viewModel.newGoodsDetailEntity.get().getCheckedItemAttr().getList().get(0).getList().size(); i++) {
                keyList.add(viewModel.newGoodsDetailEntity.get().getCheckedItemAttr().getList().get(0).getList().get(i).getName());
            }
            for (int i = 0; i < viewModel.newGoodsDetailEntity.get().getCheckedItemAttr().getList().size(); i++) {
                NewGoodsDetailEntity.SelectArr.SkuCombinationEntity skuCombinationEntity = viewModel.newGoodsDetailEntity.get().getCheckedItemAttr().getList().get(i);
                SkuCombinationEntity skuCombinationEntity1 = new SkuCombinationEntity();
                skuCombinationEntity1.setCommodity(skuCombinationEntity.getCommodity());
                skuCombinationEntity1.setId(skuCombinationEntity.getId());
                skuCombinationEntity1.setMoney(skuCombinationEntity.getMoney());
                skuCombinationEntity1.setType(skuCombinationEntity.getType());
                skuCombinationEntity1.setCategory(skuCombinationEntity.getCategory());
                skuCombinationEntity1.setUnit(skuCombinationEntity.getUnit());
                List<SkuCombinationEntity.CombinationList> skuList = new ArrayList<>();
                for (int j = 0; j < skuCombinationEntity.getList().size(); j++) {
                    SkuCombinationEntity.CombinationList combinationList = new SkuCombinationEntity.CombinationList();
                    combinationList.setName(skuCombinationEntity.getList().get(j).getName());
                    combinationList.setVal(skuCombinationEntity.getList().get(j).getVal());
                    combinationList.setValId(skuCombinationEntity.getList().get(j).getValId());
                    combinationList.setAttribute(skuCombinationEntity.getList().get(j).getAttribute());
                    skuList.add(combinationList);
                    for (int l = 0; l < keyList.size(); l++) {
                        if (keyList.get(l).equals(skuCombinationEntity.getList().get(j).getName())) {
                            SkuItemAttrEntity.Child child = new SkuItemAttrEntity.Child();
                            child.setId(keyList.get(l));
                            child.setValData(skuCombinationEntity.getList().get(j).getVal());
                            child.setValId(skuCombinationEntity.getList().get(j).getValId() + "");
                            childList.add(child);
                        }
                    }
                }
                skuCombinationEntity1.setList(skuList);
                skuCombinationEntities.add(skuCombinationEntity1);
            }

            for (int i = 0; i < childList.size(); i++) {
                itemMap.put(childList.get(i).getValId(), childList.get(i));
            }

            for (int i = 0; i < keyList.size(); i++) {
                SkuItemAttrEntity skuItemAttrEntity = new SkuItemAttrEntity();
                skuItemAttrEntity.setParamData(keyList.get(i));
                List<SkuItemAttrEntity.Child> children = new ArrayList<>();
                for (String key : itemMap.keySet()) {
                    if (keyList.get(i).equals(itemMap.get(key).getId())) {
                        SkuItemAttrEntity.Child child = new SkuItemAttrEntity.Child();
                        child.setValId(itemMap.get(key).getValId());
                        child.setValData(itemMap.get(key).getValData());
                        child.setEnabled(true);
                        children.add(child);
                    }
                }
                skuItemAttrEntity.setList(children);
                itemAttrEntityList.add(skuItemAttrEntity);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoodsEvent(GoodsEvent event) {
        if (event.getMessageTag() == EVENT_GOODS_PUBLISH) {
            if (event.getMessageTag() == EVENT_GOODS_PUBLISH) {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        viewModel.getGoodsDetail(id);
                    }
                }, 3000);//3秒后执行Runnable中的run方法

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.modify_layout:
                modifyGoodsPrice();
                break;
            case R.id.up_layout:
                getGoodsIds(OPT_UP);
                break;
            case R.id.down_layout:
                getGoodsIds(OPT_DOWN);
                break;
            case R.id.del_layout:
                getGoodsIds(OPT_DEL);
                break;
            case R.id.tv_edit:
                if (!"已上架".equals(viewModel.newGoodsDetailEntity.get().getStatus()))
                    GoodsPublishActivity.start(GoodsDetailActivity.this, id, false);
                break;
            case R.id.back_view:
            case R.id.back_view_tool_bar:
                if (JCVideoPlayer.backPress()) {
                    return;
                }
                finish();
                break;
            case R.id.ll_shop_info:
                showAttrPop();
                break;
            case R.id.rl_gg:
                showSkuPop();
                break;
        }
    }

    private void getGoodsIds(String opt) {
        List<String> goodsIds = new ArrayList<>();
        goodsIds.add(viewModel.newGoodsDetailEntity.get().getId());
        if (opt.equals(OPT_UP)) {
            String msg = "商品即将上架对外销售";
            new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                    .setTitle("温馨提示")
                    .setMsg(msg)
                    .setDialogCallBack(new CommonDialog.DialogCallBack() {
                        @Override
                        public void onRightClick() {
                            viewModel.upDowngetGoodsModel(opt, goodsIds);
                        }

                        @Override
                        public void onLeftClick() {

                        }
                    }).show();
        } else if (opt.equals(OPT_DOWN)) {
            String msg = "商品下架后，将不在平台出售";
            new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                    .setTitle("温馨提示")
                    .setMsg(msg)
                    .setDialogCallBack(new CommonDialog.DialogCallBack() {
                        @Override
                        public void onRightClick() {
                            viewModel.upDowngetGoodsModel(opt, goodsIds);
                        }

                        @Override
                        public void onLeftClick() {

                        }
                    }).show();
        } else if (opt.equals(OPT_DEL)) {
            String msg = "删除不可恢复，是否确定删除？";
            new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                    .setTitle("温馨提示")
                    .setMsg(msg)
                    .setDialogCallBack(new CommonDialog.DialogCallBack() {
                        @Override
                        public void onRightClick() {
                            viewModel.upDowngetGoodsModel(opt, goodsIds);
                        }

                        @Override
                        public void onLeftClick() {

                        }
                    }).show();
        }
    }

    private void modifyGoodsPrice() {
        new GoodsDetailPriceDialog3(getActivity(), null)
                .setPrice(viewModel.newGoodsDetailEntity.get().getPrice())
                .setUnit(viewModel.newGoodsDetailEntity.get().getUnit())
                .setDialogClickCallBack(new GoodsDetailPriceDialog3.DialogClickCallBack() {
                    @Override
                    public void onClickResult(String price) {
                        viewModel.modifyGoodsDetailPriceModel(viewModel.newGoodsDetailEntity.get().getId(), price);
                    }
                }).show();
    }

    public void optSuccess(String opt) {
        if (opt.equals(OPT_UP)) {
            viewModel.getGoodsDetail(id);
        } else if (opt.equals(OPT_DOWN)) {
            viewModel.getGoodsDetail(id);
        } else if (opt.equals(OPT_DEL)) {
            finish();
        }
    }

    public void modifySuccess() {
        viewModel.getGoodsDetail(id);
    }

    /**
     * 初始化setToolBar
     */
    private void setToolBar() {
        binding.appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                binding.toolbar.setBackgroundColor(changeAlpha(getResources().getColor
                        (R.color.color_main), Math.abs(verticalOffset * 1.0f) / appBarLayout.getTotalScrollRange()));
                binding.toolbar.setAlpha(Math.abs(verticalOffset * 1.0f) / appBarLayout
                        .getTotalScrollRange());
            }
        });
    }

    /**
     * 根据百分比改变颜色透明度
     */
    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }


    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Subscribe
    public void getCode(MessageEvent event) {
        switch (event.code) {
            case EventConstant
                    .EVENT_STATE:
                int state = (int) event.data;
                binding.rv.setVisibility((state == 0 || state == 7) ? View.VISIBLE : View.GONE);
                break;
        }
    }

    private void showWebView(String link) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(link)) {
                    binding.llWv.removeAllViews();
                    WebView webView2 = new WebView(GoodsDetailActivity.this);
                    webView2.setFocusable(true);
                    webView2.setFocusableInTouchMode(true);
                    WebSettings webSettings = webView2.getSettings();
                    if (Build.VERSION.SDK_INT >= 19) {
                        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                    }
                    webSettings.setJavaScriptEnabled(true);
                    webSettings.setDomStorageEnabled(true);
                    webSettings.setAppCacheEnabled(false);
                    binding.llWv.setVisibility(View.VISIBLE);
                    webView2.setWebViewClient(new WebViewClient() {
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            view.loadUrl(url);
                            return super.shouldOverrideUrlLoading(view, url);
                        }
                    });
                    webView2.loadUrl(StringEscapeUtils.unescapeJava(link));
                    webView2.requestLayout();
                    binding.llWv.addView(webView2);
                    webView2.setWebViewClient(new WebViewClient() {

                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            view.loadUrl(url);
                            return super.shouldOverrideUrlLoading(view, url);
                        }

                        @Override
                        public void onPageFinished(WebView view, String url) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    webView2.measure(0, 0);
                                    int measuredHeight = webView2.getMeasuredHeight();
                                    ViewGroup.LayoutParams layoutParams = webView2.getLayoutParams();
                                    layoutParams.height = measuredHeight;
                                    webView2.setLayoutParams(layoutParams);
                                }
                            }, 1000);
                        }
                    });
                    webView2.requestLayout();
                } else {
                    binding.llWv.setVisibility(View.GONE);
                }
            }
        });
    }
}